import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

export default function Register() {
  const [studentId, setStudentId] = useState('');
  const [name, setName] = useState('');
  const [birthDate, setBirthDate] = useState('');
  const [idCard, setIdCard] = useState('');
  const [address, setAddress] = useState('');
  const [password, setPassword] = useState('');
  const navigate = useNavigate();
  const { setUser } = useAuth();

  const handleRegister = async (e) => {
    e.preventDefault();
    if (studentId && idCard && password) {
      const res = await fetch('/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          student_id: studentId,
          name: name || '',
          birth_date: birthDate || '',
          id_card: idCard,
          address: address || '',
          password
        })
      });
      const data = await res.json();
      if (data.success) {
        setUser(null);
        alert('注册成功，请登录');
        navigate('/login');
      } else {
        alert(data.message || '注册失败');
      }
    } else {
      alert('学号、身份证号、密码为必填项');
    }
  };

  return (
    <div className="card" style={{ maxWidth: 400 }}>
      <h2 style={{ textAlign: 'center', marginBottom: 24 }}>注册</h2>
      <form onSubmit={handleRegister}>
        <input type="text" placeholder="学号*" value={studentId} onChange={e => setStudentId(e.target.value)} style={{ width: '100%', marginBottom: 14 }} />
        <input type="text" placeholder="姓名" value={name} onChange={e => setName(e.target.value)} style={{ width: '100%', marginBottom: 14 }} />
        <input type="date" placeholder="出生日期" value={birthDate} onChange={e => setBirthDate(e.target.value)} style={{ width: '100%', marginBottom: 14 }} />
        <input type="text" placeholder="身份证号*" value={idCard} onChange={e => setIdCard(e.target.value)} style={{ width: '100%', marginBottom: 14 }} />
        <input type="text" placeholder="地址" value={address} onChange={e => setAddress(e.target.value)} style={{ width: '100%', marginBottom: 14 }} />
        <input type="password" placeholder="密码*" value={password} onChange={e => setPassword(e.target.value)} style={{ width: '100%', marginBottom: 18 }} />
        <button type="submit" style={{ width: '100%', marginBottom: 8 }}>注册</button>
      </form>
      <div style={{ textAlign: 'right' }}>
        <a href="/login">已有账号？登录</a>
      </div>
    </div>
  );
} 